package cn.gov.ssxmzj.service;

import cn.gov.ssxmzj.entry.*;
import cn.gov.ssxmzj.mapper.*;
import cn.gov.ssxmzj.utils.DateUtils;
import cn.gov.ssxmzj.utils.StaticUtils;
import cn.gov.ssxmzj.utils.Utils;
import com.alibaba.fastjson.JSON;
import com.mysql.jdbc.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ManagerService {

    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private BeneficiaryMapper beneficiaryMapper;
    @Autowired
    private ServiceMapper serviceMapper;
    @Autowired
    private OptionMapper optionMapper;
    @Autowired
    private MsgService msgService;
    @Autowired
    private VillageMapper villageMapper;

    /**
     * 登录验证
     * @param username
     * @param password
     * @return
     */
    public Result login(String username, String password,String code, HttpSession session){
        if(Utils.isEmpty(code)||!code.equalsIgnoreCase(String.valueOf(session.getAttribute("number")))){
            return new Result(Result.ERROR,"验证码错误","");
        }
        Result checkManager = unlock(username,password);
        if(!Result.SUCCESS.equals(checkManager.getStatus())){
            return checkManager;
        }
        ManagerInfo manager = (ManagerInfo)checkManager.getData();
        //更新最后登录时间
        String managerId = manager.getManager_id();
        String lastLoginTime = DateUtils.getDate();
        ManagerInfo updateManager = new ManagerInfo();
        updateManager.setManager_id(managerId);
        updateManager.setLast_login_time(lastLoginTime);
        try{
            managerMapper.modifyManager(updateManager);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(Result.SUCCESS,"登录成功",manager);
    }

    /**
     * 解锁锁屏
     * @param username
     * @param password
     * @return
     */
    public Result unlock(String username,String password){
        if(Utils.isEmpty(username)){
            return new Result(Result.ERROR,"未获取到用户的账号","");
        }
        Map sqlMap = Utils.asMap("username",username);
        List<ManagerInfo> managerInfos = managerMapper.getManagerInfoByName(sqlMap);
        if(Utils.isEmpty(managerInfos)){
            return new Result(Result.SERVICE_ERROR,"该账号不存在","");
        }
        if(managerInfos.size()>1){
            return new Result(Result.SERVICE_ERROR,"该账号信息有误，对应多个用户，请联系管理员","");
        }
        ManagerInfo manager = managerInfos.get(0);
        if("0".equals(manager.getValid_tag())){
            return new Result(Result.SERVICE_ERROR,"该用户已被限制登录，请联系管理员","");
        }
        if(!password.equals(manager.getPassword())){
            return new Result(Result.SERVICE_ERROR,"密码不正确","");
        }
        return new Result(Result.SUCCESS,"解锁成功",manager);
    }

    /**
     * 获取管理员信息
     * @param managerId
     * @param page
     * @param limit
     * @return
     */
    public Result getManagerInfo(String managerId,String searchName,int page,int limit){
        page = 0 == page ? 0 : --page * limit;
        String isSelAll = null;
        //管理员id为空即为获取 全部信息,则不查询超级管理员信息
        if(Utils.isEmpty(managerId)){
            managerId = null;
            isSelAll = "true";
        }
        searchName = Utils.isEmpty(searchName)?null:"%"+searchName+"%";
        //获取低等级管理员的总人数
        Map sqlMap = Utils.asMap("managerId",managerId,"searchName",searchName,"isSelAll",isSelAll);
        int count = managerMapper.getManagerCount(sqlMap);
        if(count<=0){
            return new Result(Result.SERVICE_ERROR,"未查询到数据","");
        }
        //获取管理员信息
        sqlMap.putAll(Utils.asMap("page",page,"limit",limit));
        List<ManagerInfo> managerInfoList = managerMapper.getManagerInfoLimit(sqlMap);
        for(ManagerInfo info:managerInfoList){
            info.setManager_level(Utils.changeManagerLevel(info.getManager_level()));
            info.setSex(Utils.changeSex(info.getSex()));
            info.setLast_login_time(DateUtils.changeDate(info.getLast_login_time(),"yyyyMMddHHmmss","yyyy-MM-dd HH:mm:ss"));
        }
        return new Result(Result.SUCCESS,"查询成功",new PageNews(count,Utils.asMap("data",managerInfoList)));
    }

    /**
     * 管理员查询新闻
     * @param newsType
     * @param searchName
     * @param offset
     * @param rows
     * @return
     */
    public Result managerGetNewsInfo(String newsType,String searchName,int offset,int rows){
        offset = offset==0 ? 0 : --offset;
        offset = offset*rows;
        newsType = Utils.isEmpty(newsType)?null:newsType;
        searchName = Utils.isEmpty(searchName)||"0".equals(searchName)?null:"%"+searchName+"%";
        //获取有效数据总条数
        Map sqlMap = Utils.asMap("newsType",newsType,"searchName",searchName);
        int count = newsMapper.getNewsCountByType(sqlMap);
        if(count <= 0){
            return new Result(Result.SERVICE_ERROR,"暂无该内容","");
        }
        //返回新闻内容
        sqlMap.putAll(Utils.asMap("offset",offset,"rows",rows));
        List<Map<String,String>> newsData = newsMapper.managerGetAllNewsByType(sqlMap);
        return new Result(Result.SUCCESS,"查询成功",new PageNews(count,Utils.asMap("newsData",newsData)));
    }

    /**
     * 删除新闻id
     * @param newsId
     * @return
     */
    public Result deleteNews(String newsId){
        int deleteRow = newsMapper.deleteNews(newsId);
        if(deleteRow>0){
            return new Result(Result.SUCCESS,"删除成功","");
        }
        return new Result(Result.SERVICE_ERROR,"未获取到删除的新闻","");
    }

    /**
     * 修改有效标记
     * @param isValid
     * @return
     */
    public Result changeValidTag(String isValid,String dataId,String dataType,String optManagerId){
        isValid = "1".equals(isValid)?isValid:"0";
        int changeNum = 0;
        if("news".equals(dataType)){
            changeNum = newsMapper.changeNewsValidTag(Utils.asMap("isValid",isValid,"newsId",dataId));
        }else if("beneficiary".equals(dataType)){
            changeNum = beneficiaryMapper.changeBeneficiaryValidTag(Utils.asMap("isValid",isValid,"beneficiaryId",dataId));
        }else if("serviceOption".equals(dataType)){
            OptionInfo option = new OptionInfo();
            option.setOption_id(dataId);
            option.setValid_tag(isValid);
            changeNum = optionMapper.modifyOption(option);
        }else if("Manager".equals(dataType)){
            List<ManagerInfo> optManagerList = managerMapper.getManagerInfoByName(Utils.asMap("managerId",optManagerId));
            if(Utils.isEmpty(optManagerList)){
                return new Result(Result.SERVICE_ERROR,"未获取到操作员信息，请重试","");
            }
            List<ManagerInfo> managerList = managerMapper.getManagerInfoByName(Utils.asMap("managerId",dataId));
            if(Utils.isEmpty(managerList)){
                return new Result(Result.SERVICE_ERROR,"未获取到要删除的管理员信息，请重试","");
            }
            if(optManagerList.get(0).getManager_level().compareTo(managerList.get(0).getManager_level())<=0){
                return new Result(Result.SERVICE_ERROR,"对不起，您的工号暂时不能操作相同或更高等级的工号","");
            }
            ManagerInfo manager = new ManagerInfo();
            manager.setManager_id(dataId);
            manager.setValid_tag(isValid);
            changeNum = managerMapper.modifyManager(manager);
        }
        if(changeNum>0){
            return new Result(Result.SUCCESS,"修改成功","");
        }
        return new Result(Result.SERVICE_ERROR,"未获取到要操作的信息","");
    }

    /**
     * 新增新闻
     * @param newsInfo
     * @return
     */
    public Result addNews(String newsInfo,String managerId){
        if(Utils.isEmpty(Utils.checkNull(managerId))){
            return new Result(Result.SERVICE_ERROR,"登录状态已失效，请重新登录","");
        }
        Map addNews = (Map) JSON.parse(newsInfo);
        String newsId = Utils.createNewsId();//新闻Id
        String createTime = DateUtils.getDate();//创建时间
        String newsTitle = String.valueOf(addNews.get("newsTitle"));
        String newsType = String.valueOf(addNews.get("newsType"));
        String isValid = String.valueOf(addNews.get("isValid"));
        isValid = "on".equals(isValid)?"1":"0";
        String content = String.valueOf(addNews.get("content"));
        News newNew = new News(newsId,newsTitle,content,createTime,managerId,createTime,managerId,newsType,null
                                ,null,isValid,null,null);
        try {
            newsMapper.addNews(newNew);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.ERROR,"添加新闻异常,请稍后重试","");
        }
        return new Result(Result.SUCCESS,"添加成功!","");
    }

    /**
     * 修改文章内容
     * @param newsInfo
     * @param newsId
     * @return
     */
    public Result modifyNews(String newsInfo, String newsId, String managerId){
        if(Utils.isEmpty(Utils.checkNull(managerId))){
            return new Result(Result.SERVICE_ERROR,"登录状态已失效，请重新登录","");
        }
        Map addNews = (Map) JSON.parse(newsInfo);
        String newsTitle = String.valueOf(addNews.get("newsTitle"));
        String newsType = String.valueOf(addNews.get("newsType"));
        String isValid = String.valueOf(addNews.get("isValid"));
        isValid = "on".equals(isValid)?"1":"0";
        String content = String.valueOf(addNews.get("content"));

        String lastChangeTime = DateUtils.getDate();
        News news = new News(newsId,newsTitle,content,null,null,
                lastChangeTime,managerId,newsType,null
                ,null,isValid,null,null);
        try {
            newsMapper.modifyNews(news);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.ERROR,"修改新闻异常,请稍后重试","");
        }
        return new Result(Result.SUCCESS,"修改成功!","");
    }

    /**
     * 获取首页轮播图
     * @return
     */
    public Result getShowPic(int page,int number){
        //获取图片总数,newsType=5 表示为首页轮播图
        Map sqlMap = Utils.asMap("newsType","5");
        int count = newsMapper.getNewsCountByType(sqlMap);
        if(count < 1){
            return new Result(Result.SERVICE_ERROR,"暂无图片,请先上传图片","");
        }
        int offset = page==0 ? 0 : page-1;
        offset = offset*number;
        sqlMap.putAll(Utils.asMap("offset",offset,"rows",number));
        List<News> pics = newsMapper.getAllNewsByType(sqlMap);
        return new Result(Result.SUCCESS,"图片获取成功",new PageNews(count,pics));
    }

    /**
     * 添加轮播图
     * @param image
     * @param newsTitle
     * @return
     */
    public Result uploadPic(MultipartFile image, String newsTitle, String managerId){
        if(Utils.isEmpty(Utils.checkNull(managerId))){
            return new Result(Result.SERVICE_ERROR,"登录状态已失效，请重新登录","");
        }
        if(Utils.isEmpty(newsTitle)||newsTitle.length()<5){
            return new Result(Result.SERVICE_ERROR,"标题不能小于5位!","");
        }
        if(Utils.isEmpty(image)|| image.isEmpty()){
            return new Result(Result.SERVICE_ERROR,"未获取到图片内容,请重试","");
        }
        if(Utils.isEmpty(managerId)){
            return new Result(Result.SERVICE_ERROR,"未获取到管理员信息,请重试","");
        }
        String picId = Utils.createShowPicId();
        String createTime = DateUtils.getDate();
        String newsType = "5"; //5表示轮播图
        String picName = image.getOriginalFilename();
        String picType = picName.substring(picName.indexOf(".")+1);
        String newsName = "showPic"+createTime.substring(2);
        //图片的相对路径 因为图片在数据库中的路径和其在服务器上的路径不一样,下面重新拼
        String newsPicSrc = StaticUtils.SHOW_PIC_PATH+newsName+"."+picType;

        try {
            Utils.uploadFile(image, StaticUtils.IMAGE_ROOT + newsPicSrc);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.ERROR,"保存图片异常,请稍后重试","");
        }

        News pic = new News(picId,newsTitle,null,createTime,managerId,createTime,managerId,newsType,newsName,
                StaticUtils.DB_IMAGE_ROOT+newsPicSrc,
                "1",null,null);
        newsMapper.addNews(pic);
        return new Result(Result.SUCCESS,"添加成功","");
    }

    /**
     * 管理员获取新闻信息
     * @param page
     * @param limit
     * @param beneficiaryType
     * @param villageId
     * @return
     */
    public Result getBeneficiaryInfo(int page, int limit, String beneficiaryType, String villageId){
        page = 0 == page ? 0 : --page * limit;
        beneficiaryType = Utils.isEmpty(beneficiaryType)?null:beneficiaryType;
        villageId = Utils.isEmpty(villageId)||"0".equals(villageId)?null:villageId;
        Map sqlMap = Utils.asMap("beneficiaryType",beneficiaryType,"villageId",villageId);
        int count = beneficiaryMapper.getCount(sqlMap);
        if (count == 0) {
            return new Result(Result.SERVICE_ERROR,"未查询到数据","");
        }
        sqlMap.putAll(Utils.asMap("page",page,"limit",limit));
        List<Map> info = beneficiaryMapper.ManagerGetBeneficiaryInfo(sqlMap);
        for(Map i:info){
            i.put("BENEFICIARY_TYPE",Utils.changeBeneficiaryType(String.valueOf(i.get("BENEFICIARY_TYPE"))));
        }
        return new Result(Result.SUCCESS,"查询成功",new PageNews(count,Utils.asMap("data",info)));
    }

    /**
     * 管理员删除信息
     * @param beneficiaryId
     * @return
     */
    public Result deleteBeneficiary(String beneficiaryId){
        int deleteRow = beneficiaryMapper.deleteBeneficiary(beneficiaryId);
        if(deleteRow>0){
            return new Result(Result.SUCCESS,"删除成功","");
        }
        return new Result(Result.SERVICE_ERROR,"未获取到删除的信息","");
    }

    /**
     * 获取信息
     * @param dataId
     * @param dataType
     * @return
     */
    public Result getDataInfoById(String dataId,String dataType){
        List dataInfo = null;
        if("beneficiary".equals(dataType)){
            dataInfo = beneficiaryMapper.getBeneficiaryInfo(
                    Utils.asMap("beneficiaryId",dataId,"page",0,"limit",1));
        }else if("serviceOption".equals(dataType)){
            dataInfo = serviceMapper.getServiceOptionById(Utils.asMap("optionId",dataId));
        }
        if(Utils.isEmpty(dataInfo)){
            return new Result(Result.SERVICE_ERROR,"未获取到数据,请重试","");
        }
        return new Result(Result.SUCCESS,"查询成功",dataInfo);
    }
    /**
     * 新增信息
     * @param beneficiaryInfo
     * @return
     */
    public Result addBeneficiary(String beneficiaryInfo,String managerId){
        if(Utils.isEmpty(Utils.checkNull(managerId))){
            return new Result(Result.SERVICE_ERROR,"登录状态已失效，请重新登录","");
        }
        Map addBeneficiary = (Map) JSON.parse(beneficiaryInfo);
        String beneficiaryId = Utils.createBeneficiaryId();//新闻Id
        String createTime = DateUtils.getDate();//创建时间
        String beneficiaryName = String.valueOf(addBeneficiary.get("beneficiaryName"));
        String certNum = String.valueOf(addBeneficiary.get("certNum"));
        String address = String.valueOf(addBeneficiary.get("address"));
        String standards = String.valueOf(addBeneficiary.get("standards"));
        String beneficiaryType = String.valueOf(addBeneficiary.get("beneficiaryType"));
        String villageId = String.valueOf(addBeneficiary.get("villages"));
        String isValid = String.valueOf(addBeneficiary.get("isValid"));
        isValid = "on".equals(isValid)?"1":"0";
        BeneficiaryInfo beneficiary = new BeneficiaryInfo(beneficiaryId,beneficiaryName,certNum,standards,villageId,address,
                beneficiaryType,createTime,managerId,createTime,managerId,isValid,null,null);
        try {
            beneficiaryMapper.addBeneficiary(beneficiary);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.ERROR,"添加新闻异常,请稍后重试","");
        }
        return new Result(Result.SUCCESS,"添加成功!","");
    }

    /**
     * 修改受惠内容
     * @param beneficiaryInfo
     * @param beneficiaryId
     * @return
     */
    public Result modifyBeneficiary(String beneficiaryInfo, String beneficiaryId, String managerId){
        if(Utils.isEmpty(Utils.checkNull(managerId))){
            return new Result(Result.SERVICE_ERROR,"登录状态已失效，请重新登录","");
        }
        Map addBeneficiary = (Map) JSON.parse(beneficiaryInfo);

        String beneficiaryName = String.valueOf(addBeneficiary.get("beneficiaryName"));
        String certNum = String.valueOf(addBeneficiary.get("certNum"));
        String address = String.valueOf(addBeneficiary.get("address"));
        String standards = String.valueOf(addBeneficiary.get("standards"));
        String beneficiaryType = String.valueOf(addBeneficiary.get("beneficiaryType"));
        String villageId = String.valueOf(addBeneficiary.get("villages"));
        String isValid = String.valueOf(addBeneficiary.get("isValid"));
        isValid = "on".equals(isValid)?"1":"0";

        String lastChangeTime = DateUtils.getDate();
        BeneficiaryInfo beneficiary = new BeneficiaryInfo(beneficiaryId,beneficiaryName,certNum,standards,villageId,address,
                beneficiaryType,null,null,lastChangeTime,managerId,isValid,null,null);
        try {
            beneficiaryMapper.modifyBeneficiary(beneficiary);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.ERROR,"修改新闻异常,请稍后重试","");
        }
        return new Result(Result.SUCCESS,"修改成功!","");
    }

    //根据名字查询受惠信息
    public Result searchBeneficiaryByName(String searchName,String villageId,int page,int limit){
        page = 0 == page ? 0 : --page * limit;
        villageId = Utils.isEmpty(villageId)?null:villageId;
        Map sqlMap = Utils.asMap("searchName","%"+searchName+"%","villageId",villageId);
        int count = beneficiaryMapper.getCount(sqlMap);
        if(count<1){
            return new Result(Result.SERVICE_ERROR,"未查询到["+searchName+"]的信息","");
        }
        sqlMap.putAll(Utils.asMap("page",page,"limit",limit));
        List<Map> beneficiaryInfo = beneficiaryMapper.ManagerGetBeneficiaryInfo(sqlMap);
        for(Map i:beneficiaryInfo){
            i.put("BENEFICIARY_TYPE",Utils.changeBeneficiaryType(String.valueOf(i.get("BENEFICIARY_TYPE"))));
        }
        return new Result(Result.SUCCESS,"查询成功",new PageNews(count,Utils.asMap("data",beneficiaryInfo)));
    }

    /**
     * 管理员获取服务信息
     * @param serviceId
     * @return
     */
    public Result getServiceInfo(String serviceId,String serviceType){
        serviceId = Utils.isEmpty(serviceId)?null:serviceId;
        //服务类型默认2-便民服务
        Map sqlMap = Utils.asMap("serviceId",serviceId,"serviceType",serviceType);
        List<ServiceInfo> serviceInfo = serviceMapper.getServiceInfoByType(sqlMap);
        if(Utils.isEmpty(serviceInfo)){
            return new Result(Result.SERVICE_ERROR,"暂无服务信息","");
        }
        String serviceHtml = "<div class=\"layui-input-inline\">" +
                "<select id=\"services\" lay-filter=\"service-filter\" name=\"services\" lay-verify=\"required\" lay-search=\"services\">" +
                "<option value=\"\">请选择或输入服务</option>";
        for(ServiceInfo ser:serviceInfo){
            serviceHtml += "<option value=\""+ser.getService_id()+"\">"+ser.getService_name()+"</option>";
        }
        serviceHtml += "</select></div>";
        return new Result(Result.SUCCESS,"查询成功",serviceHtml);
    }

    /**
     * 管理员获取服务明细
     * @param serviceId
     * @param serviceType
     * @param page
     * @param limit
     * @return
     */
    public Result getServiceOptionInfo(String serviceId,String serviceType,String searchName,int page,int limit){
        page = 0 == page ? 0 : --page * limit;
        serviceId = Utils.isEmpty(serviceId)?"":serviceId;
        searchName = Utils.isEmpty(searchName)?null:"%"+searchName+"%";
        Map sqlMap = Utils.asMap("serviceId",serviceId,"serviceType",serviceType,"searchName",searchName);
        int count = serviceMapper.getServiceOptionCount(sqlMap);
        if(count < 1){
            return new Result(Result.SERVICE_ERROR,"暂无获取到信息","");
        }
        sqlMap.putAll(Utils.asMap("page",page,"limit",limit));
        List<Map> serviceInfo = serviceMapper.getServiceOptionInfo(sqlMap);
        return new Result(Result.SUCCESS,"查询成功",new PageNews(count,Utils.asMap("data",serviceInfo)));
    }

    /**
     * 修改服务信息
     * @param serviceInfo
     * @param optionId
     * @param managerId
     * @return
     */
    public Result modifyServiceOption(String serviceInfo, String optionId, String managerId){
        if(Utils.isEmpty(Utils.checkNull(managerId))){
            return new Result(Result.SERVICE_ERROR,"登录状态已失效，请重新登录","");
        }
        Map addServiceOption = (Map) JSON.parse(serviceInfo);
        //先判断是否为新增
        boolean isAddOption = Utils.isEmpty(optionId);

        String optionName = String.valueOf(addServiceOption.get("optionName"));
        String serviceContent = String.valueOf(addServiceOption.get("serviceContent"));
        String optionContent = String.valueOf(addServiceOption.get("optionContent"));
        String serviceId = String.valueOf(addServiceOption.get("services"));
        String isValid = String.valueOf(addServiceOption.get("isValid"));
        isValid = "on".equals(isValid)?"1":"0";

        String lastChangeTime = DateUtils.getDate();
        //先更新服务信息
        ServiceInfo service = new ServiceInfo(serviceId,null,serviceContent,null,null,
                null,lastChangeTime,managerId,null,null,null);
        String createTime = null;
        String createUser = null;
        //新建服务则创建服务id
        if(isAddOption){
            optionId = Utils.createOptionId();
            createTime = lastChangeTime;
            createUser = managerId;
        }

        //再创建服务信息
        OptionInfo option = new OptionInfo(optionId,optionName,optionContent,serviceId,createTime,createUser,lastChangeTime,
                managerId,isValid,null,null);
        try {
            serviceMapper.modifyService(service);
            if(isAddOption){
                optionMapper.addOption(option);
            }else {
                optionMapper.modifyOption(option);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.ERROR,"操作服务信息异常,请稍后重试","");
        }
        return new Result(Result.SUCCESS,"操作成功!","");
    }

    /**
     * 管理员删除服务
     * @param optionId
     * @return
     */
    public Result deleteServiceOption(String optionId){
        int deleteRow = optionMapper.deleteOption(optionId);
        if(deleteRow>0){
            return new Result(Result.SUCCESS,"删除成功","");
        }
        return new Result(Result.SERVICE_ERROR,"未获取到删除的信息","");
    }

    /**
     * 修改管理员信息
     * @param managerInfo
     * @param managerId
     * @return
     */
    public Result modifyManager(String managerInfo,String managerId,String optManagerId){
        if(Utils.isEmpty(Utils.checkNull(managerId))){
            return new Result(Result.SERVICE_ERROR,"登录状态已失效，请重新登录","");
        }
        //校验工号的权限等级
        Map modifyManagerInfo = (Map) JSON.parse(managerInfo);


        String realName = null;
        // TODO:暂时不支持真实姓名
        //String realName = Utils.checkNull(String.valueOf(modifyManagerInfo.get("realName")));
        String sex = Utils.checkNull(String.valueOf(modifyManagerInfo.get("sex")));
        String telephone = Utils.checkNull(String.valueOf(modifyManagerInfo.get("telephone")));
        String jobPost = Utils.checkNull(String.valueOf(modifyManagerInfo.get("jobPost")));
        String email = Utils.checkNull(String.valueOf(modifyManagerInfo.get("email")));
        String slogan = Utils.checkNull(String.valueOf(modifyManagerInfo.get("slogan")));

        String oldPwd = Utils.checkNull(String.valueOf(modifyManagerInfo.get("oldPwd")));
        String data = "";
        //如果是修改密码
        if(!Utils.isEmpty(oldPwd)){
            List<ManagerInfo> ma = managerMapper.getManagerInfoByName(Utils.asMap("managerId",managerId));
            if(Utils.isEmpty(ma)){
                return new Result(Result.SERVICE_ERROR,"获取用户信息异常,重新登录","");
            }
            if(!oldPwd.equals(ma.get(0).getPassword())){
                return new Result(Result.SERVICE_ERROR,"旧密码输入错误","");
            }
            data = "changePwd";
        }
        String newPwd = Utils.checkNull(String.valueOf(modifyManagerInfo.get("oldPwd")));

        String isValid = null;

        String lastChangeTime = DateUtils.getDate();

        ManagerInfo manager = new ManagerInfo(managerId,null,newPwd,realName,sex,
                null,telephone,jobPost,email,null,slogan,null,
                null,null,lastChangeTime,managerId,isValid,null,null);
        int changeNum = 0;
        try {
            changeNum = managerMapper.modifyManager(manager);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.ERROR,"修改用户信息失败","");
        }
        if(changeNum < 1){
            return new Result(Result.SERVICE_ERROR,"修改失败,请重试","");
        }
        return new Result(Result.SUCCESS,"操作成功!",data);
    }


    /**
     * 删除管理员信息
     * @param managerId
     * @return
     */
    public Result deleteManager(String managerId,String optManagerId){
        //校验管理员权限
        List<ManagerInfo> optManagerList = managerMapper.getManagerInfoByName(Utils.asMap("managerId",optManagerId));
        if(Utils.isEmpty(optManagerList)){
            return new Result(Result.SERVICE_ERROR,"未获取到操作员信息，请重试","");
        }
        List<ManagerInfo> managerList = managerMapper.getManagerInfoByName(Utils.asMap("managerId",managerId));
        if(Utils.isEmpty(managerList)){
            return new Result(Result.SERVICE_ERROR,"未获取到要删除的管理员信息，请重试","");
        }
        if(optManagerList.get(0).getManager_level().compareTo(managerList.get(0).getManager_level())<=0){
            return new Result(Result.SERVICE_ERROR,"对不起，您的工号暂时不能操作相同或更高等级的工号","");
        }
        int deleteRow = managerMapper.deleteManager(managerId);
        if(deleteRow>0){
            return new Result(Result.SUCCESS,"删除成功","");
        }
        return new Result(Result.SERVICE_ERROR,"未获取到删除的管理员信息","");
    }

    /**
     * 新增管理员
     * @param managerInfo
     * @param optManagerId
     * @return
     */
    public Result addManager(String managerInfo,String optManagerId){
        //校验管理员权限
        List<ManagerInfo> optManagerList = managerMapper.getManagerInfoByName(Utils.asMap("managerId",optManagerId));
        if(Utils.isEmpty(optManagerList)){
            return new Result(Result.SERVICE_ERROR,"未获取到操作员信息，请重试","");
        }
        Map addManagerInfo = (Map) JSON.parse(managerInfo);
        //校验工号的权限等级
        String managerLevel = String.valueOf(addManagerInfo.get("managerLevel"));
        if(managerLevel.compareTo(optManagerList.get(0).getManager_level())>0){
            return new Result(Result.SERVICE_ERROR,"对不起，您的工号权限赞不允许创建相同或更高等级的工号","");
        }

        String username = String.valueOf(addManagerInfo.get("username"));
        //判断用户名是否已存在
        List<ManagerInfo> managerInfoList = managerMapper.getManagerInfoByName(Utils.asMap("username",username));
        if(!Utils.isEmpty(managerInfoList)){
            return new Result(Result.SERVICE_ERROR,"该用户名已存在","");
        }

        // TODO:暂时不支持真实姓名 默认为管理员等级
        String realName = Utils.changeManagerLevel(managerLevel);
        //String realName = Utils.checkNull(String.valueOf(addManagerInfo.get("realName")));
        String sex = Utils.checkNull(String.valueOf(addManagerInfo.get("sex")));
        String telephone = Utils.checkNull(String.valueOf(addManagerInfo.get("telephone")));
        String jobPost = Utils.checkNull(String.valueOf(addManagerInfo.get("jobPost")));
        String email = Utils.checkNull(String.valueOf(addManagerInfo.get("email")));
        String slogan = Utils.checkNull(String.valueOf(addManagerInfo.get("slogan")));
        String password = Utils.checkNull(String.valueOf(addManagerInfo.get("pwd")));
        String isValid = String.valueOf(addManagerInfo.get("isValid"));
        isValid = "on".equals(isValid)?"1":"0";

        String createTime = DateUtils.getDate();
        String managerId = Utils.createManagerId();

        ManagerInfo manager = new ManagerInfo(managerId,username,password,realName,sex,managerLevel,
                telephone,jobPost,email, StaticUtils.DB_IMAGE_ROOT+StaticUtils.DEFAULT_USER_PIC,
                slogan,createTime,createTime,optManagerId,createTime,optManagerId,isValid,null,null);
        try {
            managerMapper.addManager(manager);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.ERROR,"创建用户失败","");
        }
        return new Result(Result.SUCCESS,"创建成功!","");
    }

    /**
     * 导入惠民资金表格
     * @param file
     * @param optManagerId
     * @return
     */
    public Result uploadFile(MultipartFile file,String optManagerId){
        //校验工号
        Result result = msgService.checkManager(optManagerId);
        if(!Result.SUCCESS.equals(result.getStatus())){
            return result;
        }
        ManagerInfo manager = (ManagerInfo) result.getData();
        //获取文件名称
        String excelName = file.getOriginalFilename();
        //获取文件类型
        String excelType = excelName.substring(excelName.indexOf("."));
        //先将文件保存到本地
        String filePath = StaticUtils.BENEFICIARY_FILE_PATH+"beneficiaryExcelTemp"+DateUtils.getDate()+excelType;
        try{
            Utils.uploadFile(file,filePath);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.ERROR,"上传文件出错，请稍后重试","");
        }
        //进行读取excel
        result = Utils.getBeneficiaryDataByExcel(filePath,villageMapper,optManagerId);
        if(!Result.SUCCESS.equals(result.getStatus())){
            return result;
        }
        List<BeneficiaryInfo> beneficiaryInfoList = (List<BeneficiaryInfo>)result.getData();
        //入库操作
        int lineNum = 0;
        try {
            lineNum = beneficiaryMapper.autoAddBeneficiary(beneficiaryInfoList);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(Result.ERROR,"入库失败，请重新上传重试","异常信息:"+e.getMessage());
        }
        return new Result(Result.SUCCESS,"导入成功!共导入数据:"+lineNum+"行","");
    }

}
